<template>
  <div class="elimination-add-container">
    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleSave">{{ route.query.id ? '修改' : '保存' }}</el-button>
      <el-button @click="handleCancel">撤销</el-button>
    </div>
    
    <!-- 表单区 -->
    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>{{ route.query.id ? '编辑淘汰管理' : '新增淘汰管理' }}</span>
        </div>
      </template>
      <el-form :model="form" label-width="90px" class="elimination-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="淘汰日期" required>
              <el-date-picker v-model="form.EliminationDate" type="date" placeholder="请选择淘汰日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="羊只类型" required>
              <el-select v-model="form.SheepTypeId" placeholder="请选择羊只类型" filterable>
                <el-option v-for="item in sheepTypeList" :key="item.Id" :label="item.TypeName || item.Name" :value="item.Id" />
              </el-select>
            </el-form-item>
          </el-col>
         
        </el-row>
        
      </el-form>
    </el-card>
    
    <!-- 表格区 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="form.details" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="SheepFilesId" label="耳号" width="120" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.SheepFilesId" placeholder="请输入耳号" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Breed" label="品种" width="120" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.Breed" placeholder="请输入品种" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="House_typeId" label="栋舍" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.House_typeId" placeholder="请选择栋舍" size="small" @change="onHouseChange(scope.row, $event)">
              <el-option v-for="item in houseList" :key="item.House_typeId" :label="item.DongsheName" :value="item.House_typeId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="Field" label="栏位" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.Field" placeholder="栏位编号" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="LeaveStatus" label="离场状态" width="100" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.LeaveStatus" placeholder="状态" size="small">
              <el-option label="已离场" :value="true" />
              <el-option label="未离场" :value="false" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="EliminationReason" label="淘汰原因" width="150" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.EliminationReason" placeholder="请输入淘汰原因" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="Handling_measuresId" label="处理措施" width="150" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.Handling_measuresId" placeholder="请选择处理措施" size="small">
              <el-option v-for="item in handlingMeasuresList" :key="item.Id" :label="item.Name" :value="item.Id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-actions">
        <el-button type="primary" @click="addDetail" icon="el-icon-plus">新增行</el-button>
      </div>
    </el-card>
    
    <!-- 备注区 -->
    <el-card class="remark-card" shadow="never">
      <el-form-item label="备注">
        <el-input v-model="form.Remark" type="textarea" placeholder="请填写备注信息" />
      </el-form-item>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Sheep_BreedingWrite, serviceRead, Sheep_BreedingRead } from '@/utils/Interceptors';
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const sheepTypeList = ref<any[]>([]); // 羊只类型下拉
const houseList = ref<any[]>([]); // 栋舍下拉
const handlingMeasuresList = ref<any[]>([]); // 处理措施下拉

const form = reactive({
  Culling_managementId: '',
  EliminationDate: '',
  SheepTypeId: '',
  Category: '淘汰单',
  Summary: '淘汰转出',
  AccountingUnitId: 0,
  BillNo: '',
  SerialNo: '',
  Remark: '',
  details: [
    {
      SheepFilesId: '',
      Breed: '',
      House_typeId: 1,
      Field: 1,
      LeaveStatus: true,
      EliminationReason: '',
      Handling_measuresId: 2,
      BirthDate: ''
    }
  ]
});

const earNumberOptions = ref<any[]>([]);

// 获取耳号列表（已移除，因为改为文本框输入）

// 耳号输入变化处理（已移除，因为改为文本框）

// 栋舍选择变化处理
const onHouseChange = (row: any, houseTypeId: number) => {
  console.log('栋舍选择变化:', houseTypeId)
}

const addDetail = () => {
  form.details.push({
    SheepFilesId: '',
    Breed: '',
    House_typeId: 1,
    Field: 1,
    LeaveStatus: true,
    EliminationReason: '',
    Handling_measuresId: 2,
    BirthDate: ''
  });
};

const removeDetail = (index: number) => {
  if (form.details.length > 1) {
    form.details.splice(index, 1);
  }
};

const handleSave = async () => {
  try {
    // 添加调试信息
    console.log('当前路由参数:', route.query)
    console.log('当前表单数据:', form)
    
    // 验证必填字段
    if (!form.EliminationDate) {
      ElMessage.error('请选择淘汰日期')
      return
    }
    if (!form.SheepTypeId) {
      ElMessage.error('请选择羊只类型')
      return
    }
    
    // 验证明细数据
    for (let i = 0; i < form.details.length; i++) {
      const detail = form.details[i]
      if (!detail.SheepFilesId) {
        ElMessage.error(`第${i + 1}行耳号不能为空`)
        return
      }
      if (!detail.Breed || detail.Breed.trim() === '') {
        ElMessage.error(`第${i + 1}行品种不能为空`)
        return
      }
      if (!detail.EliminationReason) {
        ElMessage.error(`第${i + 1}行淘汰原因不能为空`)
        return
      }
      if (!detail.Handling_measuresId) {
        ElMessage.error(`第${i + 1}行处理措施不能为空`)
        return
      }
    }
    
    // 确保明细数据完整
    form.details.forEach((detail: any) => {
      if (detail.LeaveStatus === undefined || detail.LeaveStatus === null) detail.LeaveStatus = true
      if (!detail.EliminationReason || detail.EliminationReason.trim() === '') detail.EliminationReason = '正常淘汰'
      if (!detail.Handling_measuresId) detail.Handling_measuresId = 2
    })
    
    // 构建请求数据 - 按照API文档格式
    const requestData = {
      Id: route.query.id ? Number(route.query.id) : 0, // 修改：使用Id而不是Culling_managementId
      EliminationDate: form.EliminationDate ? new Date(form.EliminationDate).toISOString() : new Date().toISOString(),
      SheepFilesId: form.details[0].SheepFilesId,
      Breed: form.details[0].Breed,
      House_typeId: Number(form.details[0].House_typeId) || 1,
      Field: Number(form.details[0].Field) || 1,
      LeaveStatus: Boolean(form.details[0].LeaveStatus),
      EliminationReason: form.details[0].EliminationReason || '正常淘汰',
      Handling_measuresId: Number(form.details[0].Handling_measuresId) || 2,
      SheepTypeId: Number(form.SheepTypeId) || 2
    }
    
    console.log('发送的数据:', JSON.stringify(requestData, null, 2))
    console.log('是否为编辑模式:', !!route.query.id)
    console.log('ID值:', route.query.id)
    
    // 根据是否为编辑模式选择不同的API路径
    let res
    if (route.query.id) {
      // 编辑模式
      const url = '/api/CullingManagement/Update/update'
      console.log('使用更新接口:', url)
      console.log('请求URL:', Sheep_BreedingWrite.defaults.baseURL + url)
      res = await Sheep_BreedingWrite.put(url, requestData)
      console.log('更新接口响应:', res)
    } else {
      // 新增模式
      const url = '/api/CullingManagement/Add/add'
      console.log('使用新增接口:', url)
      console.log('请求URL:', Sheep_BreedingWrite.defaults.baseURL + url)
      res = await Sheep_BreedingWrite.post(url, requestData)
      console.log('新增接口响应:', res)
    }
    
    if (res.data && res.data.code === 200) {
      ElMessage.success(route.query.id ? '修改成功' : '添加成功')
      router.push('/EliminationList')
    } else {
      console.error('接口返回错误:', res.data)
      ElMessage.error(res.data.msg || '操作失败')
    }
  } catch (error: any) {
    console.error('保存淘汰数据失败:', error)
    console.error('错误详情:', error?.response?.data)
    console.error('错误状态码:', error?.response?.status)
    console.error('错误信息:', error?.message)
    ElMessage.error(error?.response?.data?.msg || '操作失败')
  }
}

const handleCancel = () => {
  ElMessage.info('已撤销');
};

// 获取羊只类型
const fetchSheepTypeList = () => {
  Sheep_BreedingWrite.get('/api/SheepType/List/list').then((res: any) => {
    if (res.data && res.data.code === 200) {
      sheepTypeList.value = res.data.data || []
    }
  })
}

// 获取栋舍列表
const fetchHouseList = () => {
  Sheep_BreedingWrite.get('/api/Pen/List').then((res: any) => {
    if (res.data && res.data.code === 200) {
      houseList.value = res.data.data || []
    } else {
      houseList.value = []
    }
  }).catch((error: any) => {
    console.error('获取栋舍列表失败:', error)
    houseList.value = []
  })
}

// 获取处理措施列表
const fetchHandlingMeasuresList = () => {
  Sheep_BreedingRead.get('/api/EliminationInfo/GetHandlingMeasuresIdName').then((res: any) => {
    if (res.data && res.data.data) {
      handlingMeasuresList.value = res.data.data || []
    } else {
      // 如果接口不存在或没有数据，使用预设数据
      handlingMeasuresList.value = [
        { Id: 1, Name: '标准处理' },
        { Id: 2, Name: '特殊处理' },
        { Id: 3, Name: '隔离处理' },
        { Id: 4, Name: '销毁处理' },
        { Id: 5, Name: '无害化处理' },
        { Id: 6, Name: '深埋处理' }
      ]
    }
  }).catch((error: any) => {
    console.error('获取处理措施列表失败:', error)
    // 如果接口失败，使用预设数据
    handlingMeasuresList.value = [
      { Id: 1, Name: '标准处理' },
      { Id: 2, Name: '特殊处理' },
      { Id: 3, Name: '隔离处理' },
      { Id: 4, Name: '销毁处理' },
      { Id: 5, Name: '无害化处理' },
      { Id: 6, Name: '深埋处理' }
    ]
  })
}

// 获取详情数据（编辑模式）
const fetchDetail = async () => {
  if (!route.query.id) return
  
  try {
    // 使用正确的API路径
    const url = `/api/CullingManagement/Detail/detail/${route.query.id}`
    console.log(`获取详情: ${url}`)
    
    const res = await Sheep_BreedingWrite.get(url)
    
    if (res.data && res.data.code === 200) {
      const data = res.data.data
      console.log('获取详情成功:', data)
      
      // 填充主表数据
      form.EliminationDate = data.EliminationDate || ''
      form.SheepTypeId = data.SheepTypeId || ''
      form.Culling_managementId = data.Id || route.query.id // 确保ID正确设置
      
      // 填充明细数据 - 使用主表数据填充第一行
      form.details[0] = {
        SheepFilesId: data.SheepFilesId || '',
        Breed: data.Breed || '',
        House_typeId: data.House_typeId || 1,
        Field: data.Field || 1,
        LeaveStatus: data.LeaveStatus !== undefined ? data.LeaveStatus : true,
        EliminationReason: data.EliminationReason || '',
        Handling_measuresId: data.Handling_measuresId || 2,
        BirthDate: data.BirthDate || ''
      }
    } else {
      ElMessage.error('获取详情失败')
    }
  } catch (error: any) {
    ElMessage.error('获取详情失败')
    console.error('获取淘汰详情失败:', error)
  }
}

onMounted(() => {
  fetchSheepTypeList()
  fetchHouseList()
  fetchHandlingMeasuresList()
  
  if (route.query.id) {
    fetchDetail()
  }
})
</script>

<style scoped>
.elimination-add-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.action-bar {
  margin-bottom: 20px;
  text-align: center;
}

.form-card {
  margin-bottom: 20px;
}

.elimination-form {
  padding: 20px 0;
}

.table-card {
  margin-bottom: 20px;
}

.table-actions {
  margin-top: 10px;
  text-align: center;
}

.remark-card {
  margin-bottom: 20px;
}

.summary-section {
  background: #fff;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 4px;
  text-align: right;
  font-weight: bold;
}

.summary-section span {
  margin-left: 20px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}
</style> 